<template>
  <div class="production-simulation">
    <div class="game-header">
      <el-button :icon="ArrowLeft" @click="goBack">返回</el-button>
      <div class="game-title">
        <h1>🏭 生产流程模拟</h1>
        <p>模拟生产线流程，优化生产效率，提升管理能力</p>
      </div>
      <div class="game-stats">
        <el-statistic title="生产效率" :value="gameStats.efficiency" suffix="%" />
        <el-statistic title="完成订单" :value="gameStats.completedOrders" />
        <el-statistic title="获得积分" :value="gameStats.points" />
      </div>
    </div>

    <!-- 游戏开始界面 -->
    <div v-if="!gameStarted" class="start-screen">
      <div class="intro-panel">
        <h2>欢迎来到生产模拟游戏</h2>
        <p>你将管理一条生产线，合理安排生产流程，按时完成订单</p>
        
        <div class="game-rules">
          <h3>游戏规则：</h3>
          <ul>
            <li>🎯 按照订单要求生产产品</li>
            <li>⚙️ 合理安排生产工序</li>
            <li>⏰ 在规定时间内完成订单</li>
            <li>💰 效率越高，获得积分越多</li>
            <li>⚠️ 注意设备维护和质量控制</li>
          </ul>
        </div>

        <el-button type="primary" size="large" @click="startGame">
          开始生产
        </el-button>
      </div>
    </div>

    <!-- 游戏界面 -->
    <div v-else class="game-interface">
      <!-- 控制面板 -->
      <div class="control-panel">
        <div class="timer-section">
          <h3>⏰ 剩余时间</h3>
          <div class="timer">{{ formatTime(remainingTime) }}</div>
        </div>

        <div class="order-section">
          <h3>📋 当前订单</h3>
          <div class="order-card">
            <h4>{{ currentOrder.name }}</h4>
            <p>需求数量: {{ currentOrder.quantity }}</p>
            <p>已完成: {{ producedCount }}/{{ currentOrder.quantity }}</p>
            <el-progress :percentage="Math.round((producedCount / currentOrder.quantity) * 100)" />
          </div>
        </div>

        <div class="stats-section">
          <h3>📊 生产统计</h3>
          <div class="stat-item">
            <span>生产效率:</span>
            <strong>{{ currentEfficiency }}%</strong>
          </div>
          <div class="stat-item">
            <span>设备状态:</span>
            <el-progress :percentage="equipmentHealth" :color="getHealthColor(equipmentHealth)" />
          </div>
          <div class="stat-item">
            <span>质量合格率:</span>
            <strong>{{ qualityRate }}%</strong>
          </div>
        </div>

        <el-button type="warning" @click="maintainEquipment" :disabled="equipmentHealth > 80">
          🔧 设备维护 ({{ maintenanceCost }}金币)
        </el-button>
      </div>

      <!-- 生产线 -->
      <div class="production-line">
        <h3>🏭 生产线</h3>
        
        <!-- 工序站点 -->
        <div class="stations">
          <div 
            v-for="station in stations" 
            :key="station.id"
            class="station"
            :class="{ 
              active: station.isWorking,
              completed: station.completed,
              problem: station.hasProblem
            }"
          >
            <div class="station-icon">{{ station.icon }}</div>
            <h4>{{ station.name }}</h4>
            <div class="station-status">
              <span v-if="station.isWorking">⚙️ 工作中</span>
              <span v-else-if="station.completed">✅ 已完成</span>
              <span v-else-if="station.hasProblem">⚠️ 故障</span>
              <span v-else>⏸️ 待命</span>
            </div>
            <div v-if="station.isWorking" class="station-progress">
              <el-progress :percentage="station.progress" :show-text="false" />
              <span class="progress-time">{{ station.remainingTime }}s</span>
            </div>
            <el-button 
              v-if="!station.isWorking && canStartStation(station)"
              type="primary"
              size="small"
              @click="startStation(station)"
            >
              开始
            </el-button>
            <el-button 
              v-if="station.hasProblem"
              type="danger"
              size="small"
              @click="fixProblem(station)"
            >
              修复
            </el-button>
          </div>
        </div>

        <!-- 产品流动动画 -->
        <div class="product-flow">
          <div 
            v-for="product in productsInLine" 
            :key="product.id"
            class="product-item"
            :style="{ left: product.position + '%' }"
          >
            📦
          </div>
        </div>
      </div>

      <!-- 随机事件 -->
      <div v-if="currentEvent" class="event-panel">
        <el-alert
          :title="currentEvent.title"
          :type="currentEvent.type"
          :description="currentEvent.description"
          show-icon
          :closable="false"
        >
          <template #default>
            <el-button 
              v-for="option in currentEvent.options" 
              :key="option.label"
              :type="option.type"
              size="small"
              @click="handleEvent(option)"
            >
              {{ option.label }}
            </el-button>
          </template>
        </el-alert>
      </div>
    </div>

    <!-- 游戏结束对话框 -->
    <el-dialog
      v-model="showGameOverDialog"
      title="生产完成"
      width="600px"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div class="game-over-content">
        <div class="final-score">
          <h2>综合得分</h2>
          <div class="score-display">{{ finalScore }}</div>
          <el-rate v-model="performanceRating" disabled show-score />
        </div>

        <div class="final-stats">
          <div class="final-stat">
            <span>完成数量:</span>
            <strong>{{ producedCount }}/{{ currentOrder?.quantity }}</strong>
          </div>
          <div class="final-stat">
            <span>生产效率:</span>
            <strong>{{ currentEfficiency }}%</strong>
          </div>
          <div class="final-stat">
            <span>质量合格率:</span>
            <strong>{{ qualityRate }}%</strong>
          </div>
          <div class="final-stat">
            <span>设备健康度:</span>
            <strong>{{ equipmentHealth }}%</strong>
          </div>
        </div>

        <el-alert
          :title="`获得 ${finalScore} 积分！`"
          :type="finalScore >= 300 ? 'success' : 'warning'"
          :closable="false"
          show-icon
        />
      </div>
      <template #footer>
        <el-button @click="restartGame">再玩一次</el-button>
        <el-button type="primary" @click="goBack">返回游戏中心</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'

const router = useRouter()

// 游戏统计
const gameStats = ref({
  efficiency: 85,
  completedOrders: 23,
  points: 2890
})

// 游戏状态
const gameStarted = ref(false)
const remainingTime = ref(180) // 3分钟
const producedCount = ref(0)
const currentEfficiency = ref(100)
const equipmentHealth = ref(100)
const qualityRate = ref(100)
const maintenanceCost = ref(50)
const showGameOverDialog = ref(false)
const finalScore = ref(0)
const performanceRating = ref(3)

// 当前订单
const currentOrder = ref({
  name: '电子产品组装订单',
  quantity: 10,
  timeLimit: 180
})

// 生产工序站点
const stations = ref([
  {
    id: 1,
    name: '原料准备',
    icon: '📦',
    duration: 3,
    isWorking: false,
    completed: false,
    hasProblem: false,
    progress: 0,
    remainingTime: 3
  },
  {
    id: 2,
    name: '零件加工',
    icon: '⚙️',
    duration: 5,
    isWorking: false,
    completed: false,
    hasProblem: false,
    progress: 0,
    remainingTime: 5
  },
  {
    id: 3,
    name: '产品组装',
    icon: '🔧',
    duration: 4,
    isWorking: false,
    completed: false,
    hasProblem: false,
    progress: 0,
    remainingTime: 4
  },
  {
    id: 4,
    name: '质量检测',
    icon: '🔍',
    duration: 2,
    isWorking: false,
    completed: false,
    hasProblem: false,
    progress: 0,
    remainingTime: 2
  },
  {
    id: 5,
    name: '包装入库',
    icon: '📦',
    duration: 2,
    isWorking: false,
    completed: false,
    hasProblem: false,
    progress: 0,
    remainingTime: 2
  }
])

// 生产线上的产品
const productsInLine = ref([])

// 当前事件
const currentEvent = ref(null)

// 随机事件库
const events = [
  {
    title: '⚡ 设备过载',
    description: '生产设备运行负荷过大，需要立即处理',
    type: 'warning',
    options: [
      { label: '立即维护(-20健康度)', type: 'danger', effect: () => { equipmentHealth.value -= 20 } },
      { label: '继续运行(-效率10%)', type: 'warning', effect: () => { currentEfficiency.value -= 10 } }
    ]
  },
  {
    title: '🎯 质量问题',
    description: '检测到部分产品质量不达标',
    type: 'error',
    options: [
      { label: '返工处理(-2秒)', type: 'primary', effect: () => { remainingTime.value -= 2 } },
      { label: '放行(-质量5%)', type: 'danger', effect: () => { qualityRate.value -= 5 } }
    ]
  },
  {
    title: '💡 生产优化建议',
    description: '系统检测到可优化的生产流程',
    type: 'success',
    options: [
      { label: '采纳建议(+效率5%)', type: 'success', effect: () => { currentEfficiency.value += 5 } },
      { label: '保持现状', type: 'info', effect: () => {} }
    ]
  }
]

// 格式化时间
function formatTime(seconds) {
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins}:${secs.toString().padStart(2, '0')}`
}

// 获取健康度颜色
function getHealthColor(health) {
  if (health >= 80) return '#67c23a'
  if (health >= 50) return '#e6a23c'
  return '#f56c6c'
}

// 开始游戏
function startGame() {
  gameStarted.value = true
  producedCount.value = 0
  remainingTime.value = 180
  currentEfficiency.value = 100
  equipmentHealth.value = 100
  qualityRate.value = 100
  
  // 开始倒计时
  startTimer()
  
  // 随机触发事件
  startRandomEvents()
  
  ElMessage.success('生产开始！')
}

// 开始计时器
function startTimer() {
  const timer = setInterval(() => {
    if (remainingTime.value > 0 && gameStarted.value) {
      remainingTime.value--
      
      // 设备自然损耗
      if (remainingTime.value % 10 === 0) {
        equipmentHealth.value = Math.max(0, equipmentHealth.value - 2)
      }
      
      // 更新工作中的站点
      stations.value.forEach(station => {
        if (station.isWorking) {
          station.remainingTime--
          station.progress = Math.round(((station.duration - station.remainingTime) / station.duration) * 100)
          
          if (station.remainingTime <= 0) {
            completeStation(station)
          }
        }
      })
    } else {
      clearInterval(timer)
      if (gameStarted.value) {
        endGame()
      }
    }
  }, 1000)
}

// 随机事件
function startRandomEvents() {
  setInterval(() => {
    if (gameStarted.value && !currentEvent.value && Math.random() > 0.7) {
      currentEvent.value = events[Math.floor(Math.random() * events.length)]
    }
  }, 15000) // 每15秒检查一次
}

// 是否可以开始工序
function canStartStation(station) {
  if (station.id === 1) return true // 第一道工序始终可以开始
  
  // 需要前一道工序完成
  const prevStation = stations.value.find(s => s.id === station.id - 1)
  return prevStation && prevStation.completed
}

// 开始工序
function startStation(station) {
  station.isWorking = true
  station.completed = false
  station.remainingTime = station.duration
  station.progress = 0
  
  ElMessage.success(`${station.name} 开始工作`)
}

// 完成工序
function completeStation(station) {
  station.isWorking = false
  station.completed = true
  station.progress = 100
  
  // 随机出现问题
  if (Math.random() > 0.85 && equipmentHealth.value < 60) {
    station.hasProblem = true
    ElMessage.warning(`${station.name} 出现故障！`)
  }
  
  // 如果是最后一道工序，产品完成
  if (station.id === stations.value.length) {
    producedCount.value++
    ElMessage.success(`完成一件产品！(${producedCount.value}/${currentOrder.value.quantity})`)
    
    // 重置所有工序
    stations.value.forEach(s => {
      s.completed = false
      s.isWorking = false
      s.progress = 0
      s.remainingTime = s.duration
    })
    
    // 检查是否完成订单
    if (producedCount.value >= currentOrder.value.quantity) {
      endGame()
    }
  }
}

// 修复问题
function fixProblem(station) {
  station.hasProblem = false
  remainingTime.value -= 3
  ElMessage.success(`${station.name} 故障已修复`)
}

// 设备维护
function maintainEquipment() {
  equipmentHealth.value = Math.min(100, equipmentHealth.value + 30)
  currentEfficiency.value = Math.min(100, currentEfficiency.value + 5)
  ElMessage.success('设备维护完成')
}

// 处理事件
function handleEvent(option) {
  option.effect()
  currentEvent.value = null
  ElMessage.info(option.label)
}

// 结束游戏
function endGame() {
  gameStarted.value = false
  
  // 计算得分
  const completionBonus = (producedCount.value / currentOrder.value.quantity) * 200
  const efficiencyBonus = (currentEfficiency.value / 100) * 100
  const qualityBonus = (qualityRate.value / 100) * 100
  const healthBonus = (equipmentHealth.value / 100) * 50
  
  finalScore.value = Math.round(completionBonus + efficiencyBonus + qualityBonus + healthBonus)
  
  // 计算星级
  if (finalScore.value >= 400) {
    performanceRating.value = 5
  } else if (finalScore.value >= 350) {
    performanceRating.value = 4
  } else if (finalScore.value >= 300) {
    performanceRating.value = 3
  } else if (finalScore.value >= 250) {
    performanceRating.value = 2
  } else {
    performanceRating.value = 1
  }
  
  showGameOverDialog.value = true
  
  // 更新总体统计
  gameStats.value.points += finalScore.value
  if (producedCount.value >= currentOrder.value.quantity) {
    gameStats.value.completedOrders++
  }
  gameStats.value.efficiency = Math.round((gameStats.value.efficiency + currentEfficiency.value) / 2)
}

// 重新开始
function restartGame() {
  showGameOverDialog.value = false
  startGame()
}

// 返回
function goBack() {
  router.push('/learning/games/center')
}
</script>

<style scoped>
.production-simulation {
  padding: 20px;
  max-width: 1600px;
  margin: 0 auto;
}

.game-header {
  display: flex;
  align-items: center;
  gap: 30px;
  margin-bottom: 30px;
  padding: 24px;
  background: linear-gradient(135deg, #30cfd0 0%, #330867 100%);
  border-radius: 12px;
  color: white;
}

.game-title {
  flex: 1;
}

.game-title h1 {
  margin: 0 0 8px 0;
  font-size: 28px;
}

.game-title p {
  margin: 0;
  opacity: 0.9;
}

.game-stats {
  display: flex;
  gap: 40px;
}

.game-stats :deep(.el-statistic__head) {
  color: rgba(255, 255, 255, 0.8);
}

.game-stats :deep(.el-statistic__content) {
  color: white;
  font-weight: bold;
}

/* 开始界面 */
.start-screen {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 500px;
}

.intro-panel {
  background: white;
  border-radius: 16px;
  padding: 48px;
  max-width: 600px;
  text-align: center;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.intro-panel h2 {
  margin: 0 0 16px 0;
  font-size: 28px;
  color: #303133;
}

.intro-panel > p {
  margin: 0 0 32px 0;
  color: #606266;
  font-size: 16px;
  line-height: 1.6;
}

.game-rules {
  text-align: left;
  margin-bottom: 32px;
  padding: 24px;
  background: #f5f7fa;
  border-radius: 12px;
}

.game-rules h3 {
  margin: 0 0 16px 0;
  color: #303133;
}

.game-rules ul {
  margin: 0;
  padding-left: 24px;
  color: #606266;
  line-height: 2;
}

/* 游戏界面 */
.game-interface {
  display: grid;
  grid-template-columns: 300px 1fr;
  gap: 20px;
}

/* 控制面板 */
.control-panel {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.timer-section,
.order-section,
.stats-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.timer-section h3,
.order-section h3,
.stats-section h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  color: #303133;
}

.timer {
  font-size: 48px;
  font-weight: bold;
  text-align: center;
  color: #409eff;
  font-family: 'Consolas', monospace;
}

.order-card {
  background: #f5f7fa;
  padding: 16px;
  border-radius: 8px;
}

.order-card h4 {
  margin: 0 0 8px 0;
  color: #303133;
}

.order-card p {
  margin: 0 0 8px 0;
  color: #606266;
  font-size: 14px;
}

.stat-item {
  margin-bottom: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-item span {
  color: #606266;
  font-size: 14px;
}

.stat-item strong {
  color: #303133;
  font-size: 16px;
}

/* 生产线 */
.production-line {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.production-line h3 {
  margin: 0 0 24px 0;
  font-size: 18px;
  color: #303133;
}

.stations {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 16px;
  margin-bottom: 32px;
}

.station {
  background: #f5f7fa;
  border-radius: 12px;
  padding: 20px;
  text-align: center;
  border: 2px solid transparent;
  transition: all 0.3s ease;
}

.station.active {
  border-color: #409eff;
  background: #ecf5ff;
}

.station.completed {
  border-color: #67c23a;
  background: #f0f9ff;
}

.station.problem {
  border-color: #f56c6c;
  background: #fef0f0;
}

.station-icon {
  font-size: 48px;
  margin-bottom: 12px;
}

.station h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #303133;
}

.station-status {
  margin-bottom: 12px;
  font-size: 13px;
  color: #909399;
}

.station-progress {
  margin-bottom: 12px;
}

.progress-time {
  display: block;
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
}

/* 产品流动 */
.product-flow {
  height: 60px;
  background: linear-gradient(90deg, #f5f7fa 0%, #e4e7ed 50%, #f5f7fa 100%);
  border-radius: 8px;
  position: relative;
}

.product-item {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  font-size: 32px;
  animation: moveProduct 3s linear infinite;
}

@keyframes moveProduct {
  from {
    left: 0%;
  }
  to {
    left: 100%;
  }
}

/* 事件面板 */
.event-panel {
  grid-column: 1 / -1;
  animation: slideDown 0.3s ease;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 游戏结束 */
.game-over-content {
  padding: 20px;
}

.final-score {
  text-align: center;
  margin-bottom: 30px;
}

.final-score h2 {
  margin: 0 0 16px 0;
  color: #303133;
}

.score-display {
  font-size: 60px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 16px;
}

.final-stats {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
  margin-bottom: 24px;
}

.final-stat {
  padding: 16px;
  background: #f5f7fa;
  border-radius: 8px;
  text-align: center;
}

.final-stat span {
  display: block;
  margin-bottom: 8px;
  color: #909399;
  font-size: 14px;
}

.final-stat strong {
  font-size: 24px;
  color: #303133;
}

@media (max-width: 1200px) {
  .game-interface {
    grid-template-columns: 1fr;
  }
  
  .stations {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 768px) {
  .stations {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>

